package com.biu.zone.common.utils;


import android.text.TextUtils;

import com.biu.zone.common.bean.resp.BaseResp;
import com.blankj.utilcode.util.ToastUtils;

import cn.net.bhb.base.utils.L;
import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

/**
 * 网络请求工具类
 */

public abstract class HttpUtils {

    //接口回调
    public interface OnResultListener<T> {

        void onSuccess(T t);

        void onError(Throwable error, String msg);
    }

    //Post方式请求网络  extends BaseResp
    public static <T> void request(Single<T> observable, final OnResultListener<T> listener) {
        //        .retryWhen(new RetryWithDelay(1, 1000))
        observable.observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SingleObserver<T>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onSuccess(T t) {
                        doNext(t, listener);
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (!TextUtils.isEmpty(e.getMessage())) {
                            L.e(e.getMessage());
                            listener.onError(e, e.getMessage());
                        }
                    }
                });
    }

    private static <T> void doNext(T t, OnResultListener<T> listener) {
        BaseResp base = null;
        try {
            base = (BaseResp) t;
        } catch (Exception e) {
            e.printStackTrace();
            L.e("解析的Bean类需要继承BaseResp类 !!!");
        }
        switch (base.getCode()) {
            //成功
            case 0:
                if (listener != null) {
                    listener.onSuccess(t);
                }
                break;
            //未登录
            case 401:
            case 403:
                ToastUtils.showShort("请先登录~");
                break;
            //失败
            default:
                if (listener != null) {
                    listener.onError(new Exception(base.getMsg()), base.getMsg());
                }
                break;
        }
    }

}
